package com.eg366.nioLearn.baseSocket.chapter02.base;

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

/**
 * NetworkInterface:此类表示一个由名称和分配给此接口的 IP 地址列表组成的网络接口
 * InetAddress:此类表示互联网协议(IP)地址
 * 
 * 一个计算机可能有多个“NetworkInterface(网络接口)”，每一个网络接口（NetworkInterface）中可能关联着多个IP地址（InetAddress）。
 */
public class InetAddressExample {
	public static void main(String[] args) {
		try {
			/* 获取主机网络接口的列表 */
			Enumeration<NetworkInterface> interfaceList = NetworkInterface.getNetworkInterfaces();
			if(interfaceList == null) {
				System.out.println("-- No interfaces found --");
			} else {
				while(interfaceList.hasMoreElements()){
					/* 遍历每个网络接口，并获得该网络接口所关联的IP */
					NetworkInterface iface = interfaceList.nextElement();
					System.out.println("Interface name:" + iface.getName());
					Enumeration<InetAddress> addrList = iface.getInetAddresses();
					if(!addrList.hasMoreElements()) {
						System.out.println("\tNo address for this interface");
					}
					/* 遍历当前网络接口关联的所有IP地址，并判断是IPV4 or IPV6，打印地址。 */
					while(addrList.hasMoreElements()) {
						InetAddress address = addrList.nextElement();
						System.out
								.print("\tAddress "
										+ ((address instanceof Inet4Address ? "(V4)"
												: (address instanceof Inet6Address ? "(V6)"
														: "(?)"))));
						System.out.println(": " + address.getHostAddress());
					}
				}
			}
			System.out.println("#############################################");
			
			/* 输入参数为：域名、主机名。参数（127.0.0.1 www.baidu.com user-2f3b533fc3.） */
			System.out.println("################### InetAddress.getAllByName() #####################");
			for(String host : args) {
				System.out.println(host + ":");
				try {
					InetAddress[] addressList = InetAddress.getAllByName(host);
					for(InetAddress address : addressList) {
						System.out.println("\t" + address.getHostName() + "/" + address.getHostAddress());
					}
				} catch (UnknownHostException e) {
					System.out.println("\tUnable to find addres for :" + host);
				}
			}
			
			System.out.println("################### InetAddress.getByName() #####################");
			/* 从程序上看，getByName()返回的是getAllByName()方法中的第一个元素 */
			for(String host : args) {
				try {
					System.out.println(host + ":" + InetAddress.getByName(host).getHostAddress());
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
			}
		} catch (SocketException e) {
			System.out.println("Error getting network interfaces:" + e.getMessage());
		}
	}
}
